<template>
  <a-drawer
    v-model:visible="vdata.visible"
    width="40%"
    :title="'新建福分规则'"
    :confirm-loading="vdata.btnLoading"
    :maskClosable="false"
    @ok="handleOkFunc"
  >
    <a-form
      ref="formRef"
      :model="vdata.saveObject"
      labelAlign="left"
      :wrapper-col="{ span: 22 }"
      layout="vertical"
      :rules="vdata.rules"
      style="margin: 30px 0 30px 20px"
    >
      <a-row>
        <a-col :span="12">
          <a-form-item label="机构" name="agentNo">
            <a-select v-model:value="vdata.saveObject['agentNo']" :disabled="!vdata.isAdd" :options="vdata.agentLiteOptions" placeholder="请选择机构" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="规则名称" name="nameAndKey">
            <a-select v-model:value="vdata.saveObject['nameAndKey']" labelInValue :options="vdata.ruleKeyOptions" :fieldNames="{ label: 'configName', value: 'configKey' }" placeholder="请选择key" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="奖励福分" name="key">
            <a-input v-model:value="vdata.saveObject['key']" placeholder="请输入奖励福分" />
          </a-form-item>
        </a-col>
        <template v-if="vdata.saveObject['nameAndKey']?.value === 'sign'">
          <a-col :span="12">
            <a-form-item label="是否有连续签到奖励" name="isKeyLink">
              <a-radio-group v-model:value="vdata.saveObject['isKeyLink']">
                <a-radio :value="0">否</a-radio>
                <a-radio :value="1">是</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <template v-if="vdata.saveObject['isKeyLink'] === 1">
            <a-col :span="12">
              <a-form-item label="连续签到天数" name="period">
                <a-input v-model:value="vdata.saveObject['period']" placeholder="请输入连续签到天数" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="连续签到奖励福分" name="keyLink">
                <a-input v-model:value="vdata.saveObject['keyLink']" placeholder="请输入连续签到奖励福分" />
              </a-form-item>
            </a-col>
          </template>
        </template>
        <a-col :span="12">
          <a-form-item label="状态" name="state">
            <a-select v-model:value="vdata.saveObject['state']" placeholder="请选择活动状态">
              <a-select-option :value="0">不启用</a-select-option>
              <a-select-option :value="1">启用</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="福分过期规则类型" name="overType">
            <a-select v-model:value="vdata.saveObject['overType']" placeholder="请选择福分过期规则类型" allowClear>
              <a-select-option :value="0">n天后过期</a-select-option>
              <a-select-option :value="1">指定过期时间</a-select-option>
              <a-select-option :value="2">次季度首月月底失效</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.saveObject['overType'] === 0" :span="12">
          <a-form-item label="有效天数" name="overDays">
            <a-input-number v-model:value="vdata.saveObject['overDays']" placeholder="有效天数" style="width: 100%;" />
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.saveObject['overType'] === 1" :span="12">
          <a-form-item label="过期时间" name="overTime">
            <a-date-picker v-model:value="vdata.saveObject['overTime']" valueFormat="YYYY-MM-DD" :disabled-date="(current)=>current && current < dayjs().endOf('day')" style="width: 100%;" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="福分规则描述" name="scoreRuleDes" :wrapper-col="{ span: 23 }">
            <a-textarea v-model:value="vdata.saveObject['scoreRuleDes']" :rows="4" placeholder="请输入规则描述" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" name="remark" :wrapper-col="{ span: 23 }">
            <a-textarea v-model:value="vdata.saveObject['remark']" :rows="4" placeholder="请输入备注" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right:8px" @click="onClose">
        <close-outlined />
        取消
      </a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc">
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { $scoreRuleAddorEdit, API_SCORE_RULE_SAVE,API_SCORE_RULE_UPDATE,$getScoreRuleInfo,$getScoreRuleKeyList,$getOfficialList} from '@/api/score/scoreRule/index'
import { ref, reactive, getCurrentInstance } from 'vue'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
import dayjs from 'dayjs'
const props = defineProps({
  callbackFunc: { type: Function, default: null }
})
const formRef = ref()
const vdata:any = reactive({
  btnLoading: false, // 显示确定按钮loading图标
  isAdd: true, // 新增 or 修改页面标识
  visible: false, // 是否显示弹层/抽屉
  saveObject: {}, // 数据对象
  recordId: null, // 更新对象ID
  rules: {
    nameAndKey: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
    key: [{ required: true, message: '奖励福分不能为空', trigger: 'blur' }],
    isKeyLink: [{ required: true, message: '请选择是否有连续签到奖励', trigger: 'blur' }],
    period: [{ required: true, message: '连续签到天数不能为空', trigger: 'blur' }],
    keyLink: [{ required: true, message: '连续签到奖励福分不能为空', trigger: 'blur' }],
    scoreName: [{ required: true, message: '福分别名不能为空', trigger: 'blur' }],
    scoreRatio: [{ required: true, message: '兑换比例不能为空', trigger: 'blur' }],
    isDefault: [{ required: true, message: '请选择是否默认', trigger: 'blur' }],
    state: [{ required: true, message: '请选择状态', trigger: 'blur' }],
    agentNo: [{ required: true, message: '请选择机构', trigger: 'blur' }],
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
    scoreRuleDes: [{ required: true, message: '规则描述不能为空', trigger: 'blur' }],
    overType: [{ required: true, message: '请选择福分过期规则类型', trigger: 'blur' }],
    overDays: [{ required: true, message: '有效天数不能为空', trigger: 'blur' }],
    overTime: [{ required: true, message: '过期时间不能为空', trigger: 'blur' }]
  },
  ruleKeyOptions: [], // 福分key列表
})

function handleOkFunc() { // 点击【确认】按钮事件
  formRef.value.validate().then(() => {
    const reqData = JSON.parse(JSON.stringify(vdata.saveObject))
    const { nameAndKey, key, keyLink, period } = reqData
    if(reqData.nameAndKey.value === 'sign'){
      reqData.ruleJson = JSON.stringify({ [nameAndKey.value]: key, [nameAndKey.value+'Link']: keyLink, period }).replace(/\//g,'')
    }else{
      reqData.ruleJson = JSON.stringify({ [nameAndKey.value]: key }).replace(/\//g,'')
    }
    reqData.scoreRuleName = nameAndKey.label
    reqData.ruleKey = nameAndKey.value
    const message = vdata.isAdd ? '新增成功' : '修改成功'
    const url = vdata.isAdd ? API_SCORE_RULE_SAVE : API_SCORE_RULE_UPDATE
    vdata.btnLoading = true
    $scoreRuleAddorEdit(url,reqData).then(res => {
      $infoBox.message.success(message)
      props.callbackFunc()
      onClose()
    }).finally(()=>{
      vdata.btnLoading = false
    })
  }).catch(()=>{})
}

function onClose(){
  vdata.visible = false
}

function show(scoreRuleId) { // 弹层打开事件
  // 请求福分key列表
  getScoreKeyList()
  // 请求小程序列表
  getAgentList()
  // 数据清空
  vdata.saveObject = {
    isKeyLink: 0
  }
  vdata.isAdd = !scoreRuleId
  vdata.btnLoading = false // 关闭loading
  // 清空验证规则
  if (formRef.value !== undefined) {
    formRef.value.resetFields()
  }

  if(!vdata.isAdd){
    $getScoreRuleInfo({ scoreRuleId }).then(res => {
      const { ruleKey, scoreRuleName } = res
      const ruleJson = JSON.parse(res.ruleJson)
      if(ruleJson.hasOwnProperty(`${ruleKey}Link`) && ruleJson.hasOwnProperty('period')){
        vdata.saveObject.isKeyLink = 1
        vdata.saveObject.period = ruleJson.period
        vdata.saveObject.keyLink = ruleJson[ruleKey+'Link']
      }
      res.key = ruleJson[ruleKey]
      res.nameAndKey = { label: scoreRuleName, value: ruleKey }
      Object.assign(vdata.saveObject,res)
      vdata.visible = true
    })
  }else{
    vdata.visible = true
  }
}

/**
 * 请求福分key列表
 */
function getScoreKeyList() {
  $getScoreRuleKeyList('').then(res => {
    vdata.ruleKeyOptions = res
  })
}
/**
 * 拉取机构小程序列表
 */
function getAgentList() {
  return $getOfficialList({ type: 1,isDeleted :0,isDefault:1 }).then((res) => {
    vdata.agentLiteOptions = res.map((item) => ({ label: item.agentName, value: item.agentNo }))
  })
}
defineExpose({ show })
</script>
